import { app, BrowserWindow } from 'electron'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))
process.env.APP_ROOT = path.join(__dirname, '..')
export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

import WebSocket from 'ws' //electron和python进行通讯使用WebSocket通讯协议
const ws = new WebSocket('ws://localhost:8765'); //使用8765端口

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST


let win: BrowserWindow | null

function createWindow() {
  //窗体初始化
  win = new BrowserWindow({
    width:1920,
    height:1080,
    icon: path.join(process.env.VITE_PUBLIC, 'electron-vite.svg'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
      nodeIntegration: false, // 禁用 Node.js 集成
      contextIsolation: true, // 启用上下文隔离
    },
  })
  //向渲染进程发送信息
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', (new Date).toLocaleString())
  })
  //转载页面
  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL)
  } else {
    win.loadFile(path.join(RENDERER_DIST, 'index.html'))
  }
  //python之间的通讯协议
  //连接成功
  ws.on('open', () => {
    console.log('WebSocket connected');
    ws.send('Hello from Electron');
  });
  //连接信号
  ws.on('message', (data) => {
    console.log('Received from Python:', data.toString('utf-8'));
    win?.webContents.send('variable-update', data.toString('utf-8'));
  });
  //连接错误
  ws.on('error', (err) => {
    console.error('WebSocket error:', err);
  });
  //连接关闭
  ws.on('close', () => {
    console.log('WebSocket connection closed');
  });
  //向渲染页面发送信息
  // 初始化变量
  let sharedVariable = 0;

  // 模拟变量的变化
  // setInterval(() => {
  //   sharedVariable += 1;
  //   }, 1000);
}

//从渲染页面接受信息

//app所有程序关闭
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    win = null
  }
})
//app所有程序启动
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})


//启动
app.whenReady().then(createWindow)
